from django.http import HttpResponse
from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView
from libs.captcha.captcha import captcha
from libs.yuntongxun.sms import CCP
#from libs.captcha.captcha import generate_captcha
from django_redis import get_redis_connection

from verifications.serializers import RegisterSmsCodeSerializer
from . import contants


class RegisterImageCodeAPIView(APIView):

    def get(self,request,image_code_id):
        text, image = captcha.generate_captcha()
        redis_conn= get_redis_connection('code')
        redis_conn.setex('img_%s'%image_code_id,contants.IMAGECODEEXPIRE,text)

        return HttpResponse(image,content_type='image/jpeg')


class RegisterSmsCodeAPIView(APIView):
    def get(self,request,mobile):
        query_params=request.query_params

        serializer = RegisterSmsCodeSerializer(data=query_params)
        serializer.is_valid(raise_exception=True)

        from random import randint
        sms_code = '%06d'%randint(0,999999)

        CCP().send_template_sms(mobile,[sms_code,5],1)

        redis_conn=get_redis_connection('code')
        redis_conn.setex('sms_%s'%mobile,300,sms_code)
        return Response({'msg':'ok'})


